#include "connectiondialog.h"
#include "ui_connectiondialog.h"
#include <QSettings>
#include <QPushButton>
#include "mainwindow.h"
#include "logic.h"
#include <QCloseEvent>


#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <linux/hdreg.h>
#include <QMessageBox>
#include <sys/ioctl.h>
#include <QFile>

ConnectionDialog::ConnectionDialog(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::ConnectionDialog)

{
    m_ui->setupUi(this);
    setWindowTitle(tr("Подключение к базе данных"));

    QSettings settings;

    settings.beginGroup("connection");
    m_ui->leDBServer->setText(settings.value("Host", "127.0.0.1").toString());
    m_ui->leDBName->setText(settings.value("DBName", "").toString());
    m_ui->leUserName->setText(settings.value("UserName", "").toString());
    m_ui->cbRememberPasswd->setChecked(settings.value("RememberPasswd", "").toBool());
    if(m_ui->cbRememberPasswd->isChecked())
        m_ui->lePasswd->setText(settings.value("Passwd","").toString());
    else
        m_ui->lePasswd->setText("");
    settings.endGroup();

    if (!m_ui->leDBServer->text().isEmpty()) {
        m_ui->leDBName->setFocus();
        if (!m_ui->leDBName->text().isEmpty()) {
            m_ui->leUserName->setFocus();
            if (!m_ui->lePasswd->text().isEmpty()){
                m_ui->buttonBox->button(QDialogButtonBox::Ok)->setFocus();
            }
        }
    }
}

ConnectionDialog::~ConnectionDialog()
{
    delete m_ui;
}

void ConnectionDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

  //  MainWindow *mainWindow = new MainWindow(0);
 //  mainWindow->show();
//    qApp->setActiveWindow(mainWindow);


void ConnectionDialog::accept() {
    if (logic::openDB(m_ui->leDBServer->text(), m_ui->leDBName->text(),
                      m_ui->leUserName->text(), m_ui->lePasswd->text()) ) {
        saveSettings();
    }
    m_ui->lePasswd->setText("");
    this->hide();
    this->setResult(QDialog::Accepted);
    //if(!checkHDSerial()) {
    //    QMessageBox::warning(this, tr("Система защиты программы"),
    //                         tr("Ваша копия программного продукта не является зарегистрированной."
    //                            "За подробностями обращайтесь в техподдержку данного продукта по электронному адресу: squ.sub@gmail.com"),
    //                         QMessageBox::Ok, QMessageBox::Ok);
    //    exit(1);
    //}
}

void ConnectionDialog::saveSettings()
{
    QSettings settings;
    settings.beginGroup("connection");
    settings.setValue("Host", m_ui->leDBServer->text());
    settings.setValue("DBName", m_ui->leDBName->text());
    settings.setValue("UserName", m_ui->leUserName->text());
    if (m_ui->cbRememberPasswd->isChecked()){
        settings.setValue("RememberPasswd", true);
        settings.setValue("Passwd", m_ui->lePasswd->text());
    }
    else {
        settings.setValue("RememberPasswd", false);
        settings.setValue("Passwd", "");
    }
    settings.endGroup();
}


//bool checkHDSerial() {
//
//    QString hdSerial = logic::hdSerial();
//
//    AddHdSerial(hdSerial);
//
//    QSqlQuery query;
//    QString queryStr = QString("SELECT 1 FROM registration WHERE hdserial = '%1'")
//                  .arg((logic::hashPasswd(hdSerial).replace("'","\\\'")));
//    query.prepare(queryStr);
//
//    if (!query.exec()) {
//        qCritical() << "Sql Execute Error: " + query.lastQuery() + "\n" +query.lastError().text();
//    }
//    else {
//        if (query.next()){
//            return 1;
//        }
//    }
//    return false;
//}

//bool AddHdSerial(QString hdSerial)
//{
//    QSqlQuery query;
//    QString strQuery = QString("INSERT INTO registration (name, hdserial) VALUES (\"Vasy\", \'%1\')")
//               .arg((logic::hashPasswd(hdSerial)).replace("'","\\\'"));
//    query.exec(strQuery);
//    if (query.lastError().text().isEmpty()) {
//        qDebug() << "ERRORRRR";
//        return 0;
//    }
//    return 1;
//}

